package org.ku.hero.util;

import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import java.util.TimeZone;

public class ByteUtil {

    public static String byteToString(byte[] data){
        return new String(data, StandardCharsets.UTF_8);
    }

    public static int toUnsignedInt(byte dd){
        return dd & 0xFF;
    }

    /**
     * 获取BCC校验码
     * @param data
     * @param start 开始位置
     * @param end 需要校验数据的数量
     * @return
     */
    public static boolean valid2Bcc(byte[] data,int start, int end,byte target){
        return Integer.toOctalString(getBcc(data,start,end)).equals(Integer.toOctalString(target));
    }

    public static byte getBcc(byte[] data,int start, int end){
        byte[] bcc = new byte[1];
        for (int i = start; i < data.length; i++) {
            if (i == end)
                break;
            bcc[0] = (byte)(bcc[0] ^ data[i]);
        }
        return bcc[0];
    }

    /**
     *  时间定义,每个均为1个字节,采用GMT+8时间
     *  年       0～99
     *  月       1～12
     *  日       1～31
     *  小时   0～23
     *  分钟   0～59
     *  秒       0～59
     */
    public static byte[] getCurTime(){
        byte[] time = new byte[6];
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
        int year = calendar.get(Calendar.YEAR);
        time[0] = (byte) Integer.parseInt((year+"").substring(2));
        int month = calendar.get(Calendar.MONTH)+1;
        time[1] = (byte)month;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        time[2] = (byte)day;
        int hour = calendar.get(Calendar.HOUR_OF_DAY);
        time[3] = (byte)hour;
        int minute = calendar.get(Calendar.MINUTE);
        time[4] = (byte)minute;
        int second = calendar.get(Calendar.SECOND);
        time[5] = (byte)second;
        return time;
    }

    public static String timeToStr(byte[] time){
        return String.format("%s年%s月%s日%s时%s分%s秒",time[0],time[1],time[2],time[3],time[4],time[5]);
    }

    public static void main(String[] args) {
        System.out.println(timeToStr(getCurTime()));
    }
}
